<?php

/**
 * 电商平台调用端
 */
class PlatformAPIClient {

    /**
     * 组件名称
     */
    const COMPONENT_NAME = 'PlatformAPIClient';

    /**
     * 店铺的调用信息配置
     * @var type 
     */
    private static $_shopConfigs = [];

    /**
     * client instances
     * @var type 
     */
    private static $_clients = [];
    
    /**
     * cache handler
     * @var type 
     */
    private static $_cache = null;

    /**
     * 添加文件类加载规则
     */
    private static function _registerAutoload() {
        static $_isInited = false;
        if (false === $_isInited) {
            $_isInited = true;
            include dirname(__FILE__) . '/' . self::COMPONENT_NAME . '/autoload.php';
        }
    }

    /**
     * 工厂
     * @param type $platform
     * @param type $option
     * @return PlatformAPIClient_Abstract
     */
    public static function factory($platform, $option) {

        // 检查参数
        $platform = ucfirst($platform);
        if ($platform == 'Abstract' || !preg_match('/^\w{1,64}$/', $platform)) {
            throw new Exception("Bad component name: $platform");
        }

        // 获取实例
        $class = self::COMPONENT_NAME . '_' . $platform;
        $abstractClass = self::COMPONENT_NAME . '_Abstract';

        // 非 composer 模式，自己注册加载规则
        if (!class_exists($class)) {
            self::_registerAutoload();
        }

        try {
            if (class_exists($class)) {
                $object = new $class($option);
                if ($object instanceof $abstractClass) {
                    return $object;
                }
            }
        } catch (Exception $e) {
            throw new Exception('Component init failed: ' . $e->getMessage());
        }

        throw new Exception("Component does not exist: $platform");
    }

    /**
     * 设置店铺的配置信息
     * @param type $shopConfigs
     */
    public static function setShopConfigs($shopConfigs) {

        self::$_shopConfigs = $shopConfigs;
    }

    /**
     * 获取店铺API操作的client
     * @param type $shopName
     * @return PlatformAPIClient_Abstract
     */
    public static function getClientByShop($shopName) {

        if (empty(self::$_shopConfigs[$shopName])) {
            throw new Exception("Not configured shop name: $shopName");
        }

        // 通过配置创建，并维护唯一实例
        $platform = self::$_shopConfigs[$shopName]['platform'];
        $clientConfig = self::$_shopConfigs[$shopName]['option'];
        $hashKey = md5(json_encode($clientConfig));
        if (isset(self::$_clients[$hashKey])) {
            return self::$_clients[$hashKey];
        }
        $client = self::factory($platform, $clientConfig);
        self::$_clients[$hashKey] = $client;
        return $client;
    }
    
    /**
     * 设置一个缓存处理对象，需要包含 set / get / delete 方法，且 value 支持 数组 格式
     * set($key, $value, $expire)
     * get($key)
     * delete($key)
     * @param type $cache
     */
    public static function setCacheHandler($cache) {
        
        if (is_object($cache) && function_exists($cache, 'set') && function_exists($cache, 'get')) {
            self::$_cache = $cache;
        }
    }
    
    /**
     * 获取缓存处理对象
     * @return SimpleFileCache
     */
    public static function getCacheHandler() {
        
        // 未设置？
        // 初始化一个内置的简单文件缓存处理对象
        if (!self::$_cache) {
            require_once dirname(__FILE__).'/third-lib/SimpleFileCache.php';
            self::$_cache = new SimpleFileCache();
        }
        
        return self::$_cache;
    }

}
